package com.molyfun.parents.fragment.dialog;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;

import com.molyfun.parents.R;


/**
 * 选择日期弹窗dialog
 */
public class DatePickerDialogFragment extends DialogFragment implements View.OnClickListener {

    private static DatePickerDialogFragment newInstance() {
        DatePickerDialogFragment fragment = new DatePickerDialogFragment();
        return fragment;
    }

    private DatePicker mDatePicker;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_date_picker_dialog, container, false);
        (view.findViewById(R.id.tv_choose_datePicker)).setOnClickListener(this);
        (view.findViewById(R.id.close)).setOnClickListener(this);
        mDatePicker = (DatePicker) view.findViewById(R.id.datePicker);
        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_choose_datePicker:
                int month = mDatePicker.getMonth() + 1;
                int day = mDatePicker.getDayOfMonth();
                String date = mDatePicker.getYear() + "-" + (month > 9 ? month : 0 + "" + month) + "-" + (day > 9 ? day : 0 + "" + day);
                if (dateCallback != null) {
                    dateCallback.onTimeChoosed(date);
                }
                break;
            case R.id.close:
                break;
        }
        getDialog().dismiss();
    }

    private IDateCallback dateCallback;

    public void setDateCallback(IDateCallback dateCallback) {
        this.dateCallback = dateCallback;
    }

    public static class DatePickerDialogBuilder {
        private DatePickerDialogFragment mDatePickerDialogFragment;
        private String mTag;

        public DatePickerDialogBuilder() {
            mDatePickerDialogFragment = newInstance();
            mTag = "data_picker_dialot";
        }

        public DatePickerDialogBuilder setCallback(IDateCallback callback) {
            mDatePickerDialogFragment.setDateCallback(callback);
            return this;
        }

        public void build(FragmentTransaction fragmentTransaction) {
            fragmentTransaction.add(mDatePickerDialogFragment, mTag);
            fragmentTransaction.commitAllowingStateLoss();
        }
    }

    public interface IDateCallback {
        public void onTimeChoosed(String time);
    }


}
